package com.xp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xp.entity.Role;
import com.xp.entity.UserRole;
import com.xp.service.RoleService;
import com.xp.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;

/**
 * 角色管理控制器
 * 
 * @author xp
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/roles")
@RequiredArgsConstructor
@Validated
@Tag(name = "角色管理", description = "角色增删改查、用户角色关联管理等接口")
public class RoleController {

    private final RoleService roleService;

    /**
     * 分页查询角色列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询角色列表", description = "支持按角色名称和状态筛选的分页查询")
    public Result<IPage<Role>> getRolePage(
            @Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "角色名称") @RequestParam(required = false) String roleName,
            @Parameter(description = "状态：0-禁用，1-启用") @RequestParam(required = false) Integer status) {
        
        Page<Role> page = new Page<>(current, size);
        return roleService.getRolePage(page, roleName, status);
    }

    /**
     * 获取所有启用的角色
     */
    @GetMapping("/enabled")
    @Operation(summary = "获取启用角色列表", description = "获取所有状态为启用的角色列表")
    public Result<List<Role>> getEnabledRoles() {
        return roleService.getEnabledRoles();
    }

    /**
     * 根据ID获取角色详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取角色详情", description = "根据角色ID获取角色详细信息")
    public Result<Role> getRoleById(@Parameter(description = "角色ID", required = true) @PathVariable Long id) {
        return roleService.getRoleById(id);
    }

    /**
     * 新增角色
     */
    @PostMapping
    @Operation(summary = "新增角色", description = "创建新的系统角色")
    public Result<Object> createRole(@Valid @RequestBody RoleRequest request) {
        Role role = new Role();
        role.setRoleName(request.getRoleName());
        role.setRoleCode(request.getRoleCode());
        role.setDescription(request.getDescription());
        role.setStatus(request.getStatus());
        role.setSortOrder(request.getSortOrder());
        
        return roleService.createRole(role);
    }

    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新角色", description = "更新指定角色的信息")
    public Result<Object> updateRole(
            @Parameter(description = "角色ID", required = true) @PathVariable Long id,
            @Valid @RequestBody RoleRequest request) {
        
        Role role = new Role();
        role.setId(id);
        role.setRoleName(request.getRoleName());
        role.setRoleCode(request.getRoleCode());
        role.setDescription(request.getDescription());
        role.setStatus(request.getStatus());
        role.setSortOrder(request.getSortOrder());
        
        return roleService.updateRole(role);
    }

    /**
     * 更新角色状态
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "更新角色状态", description = "更新指定角色的启用/禁用状态")
    public Result<Object> updateRoleStatus(
            @Parameter(description = "角色ID", required = true) @PathVariable Long id,
            @Valid @RequestBody StatusRequest request) {
        return roleService.updateRoleStatus(id, request.getStatus());
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除角色", description = "删除指定的角色")
    public Result<Object> deleteRole(@Parameter(description = "角色ID", required = true) @PathVariable Long id) {
        return roleService.deleteRole(id);
    }

    /**
     * 获取用户的角色列表
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户角色", description = "获取指定用户的角色列表")
    public Result<List<Role>> getUserRoles(@Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        return roleService.getRolesByUserId(userId);
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/assign")
    @Operation(summary = "分配用户角色", description = "为用户分配一个或多个角色")
    public Result<Object> assignRolesToUser(@Valid @RequestBody UserRoleAssignRequest request) {
        return roleService.assignRolesToUser(request.getUserId(), request.getRoleIds());
    }

    /**
     * 为角色分配用户
     */
    @PostMapping("/assign-users")
    @Operation(summary = "为角色分配用户", description = "为指定角色分配一个或多个用户")
    public Result<Object> assignUsersToRole(@Valid @RequestBody RoleUserAssignRequest request) {
        return roleService.assignUsersToRole(request.getRoleId(), request.getUserIds());
    }

    /**
     * 移除用户角色
     */
    @DeleteMapping("/user/{userId}/role/{roleId}")
    @Operation(summary = "移除用户角色", description = "移除用户的指定角色")
    public Result<Object> removeUserRole(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "角色ID", required = true) @PathVariable Long roleId) {
        return roleService.removeUserRole(userId, roleId);
    }

    /**
     * 获取用户角色关联列表
     */
    @GetMapping("/user-roles")
    @Operation(summary = "获取用户角色关联", description = "获取用户角色关联列表")
    public Result<List<UserRole>> getUserRoleList(
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "角色ID") @RequestParam(required = false) Long roleId) {
        return roleService.getUserRoleList(userId, roleId);
    }

    /**
     * 角色请求DTO
     */
    public static class RoleRequest {
        
        @NotBlank(message = "角色名称不能为空")
        @Parameter(description = "角色名称", required = true)
        private String roleName;

        @NotBlank(message = "角色编码不能为空")
        @Parameter(description = "角色编码", required = true)
        private String roleCode;

        @Parameter(description = "角色描述")
        private String description;

        @Parameter(description = "状态：0-禁用，1-启用")
        private Integer status;

        @Parameter(description = "排序号")
        private Integer sortOrder;

        // Getter and Setter methods
        public String getRoleName() {
            return roleName;
        }

        public void setRoleName(String roleName) {
            this.roleName = roleName;
        }

        public String getRoleCode() {
            return roleCode;
        }

        public void setRoleCode(String roleCode) {
            this.roleCode = roleCode;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public Integer getSortOrder() {
            return sortOrder;
        }

        public void setSortOrder(Integer sortOrder) {
            this.sortOrder = sortOrder;
        }
    }

    /**
     * 用户角色分配请求DTO
     */
    public static class UserRoleAssignRequest {
        
        @NotNull(message = "用户ID不能为空")
        @Parameter(description = "用户ID", required = true)
        private Long userId;

        @Parameter(description = "角色ID列表")
        private List<Long> roleIds;

        // Getter and Setter methods
        public Long getUserId() {
            return userId;
        }

        public void setUserId(Long userId) {
            this.userId = userId;
        }

        public List<Long> getRoleIds() {
            return roleIds;
        }

        public void setRoleIds(List<Long> roleIds) {
            this.roleIds = roleIds;
        }
    }

    /**
     * 角色用户分配请求DTO
     */
    public static class RoleUserAssignRequest {
        
        @NotNull(message = "角色ID不能为空")
        @Parameter(description = "角色ID", required = true)
        private Long roleId;

        @Parameter(description = "用户ID列表")
        private List<Long> userIds;

        // Getter and Setter methods
        public Long getRoleId() {
            return roleId;
        }

        public void setRoleId(Long roleId) {
            this.roleId = roleId;
        }

        public List<Long> getUserIds() {
            return userIds;
        }

        public void setUserIds(List<Long> userIds) {
            this.userIds = userIds;
        }
    }

    /**
     * 状态更新请求DTO
     */
    public static class StatusRequest {
        
        @NotNull(message = "状态不能为空")
        @Parameter(description = "状态：0-禁用，1-启用", required = true)
        private Integer status;

        // Getter and Setter methods
        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }
    }
}